//
//  HomeViewController.m
//  FBSocialProject
//
//  Created by ZhangXiaofei on 2017/8/2.
//  Copyright © 2017年 YunJing. All rights reserved.
//

#import "FBCameraHomeViewController.h"
#import "FBCameraViewUtils.h"
#import "FBCameraImageViewController.h"
#import "FBCameraProgressView.h"
#define kHEXAColor(rgbValue, a) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:a]

@interface FBCameraHomeViewController ()
@property (nonatomic, copy) FBCameraPickeImageHandler imageHandler;
@property (nonatomic, copy) FBCameraPickeVideoHandler videoHandler;

@property (strong, nonatomic) LLSimpleCamera *camera;
@property (strong, nonatomic) UILabel *errorLabel;
@property (strong, nonatomic) UIImageView *snapButton;
@property (strong, nonatomic) UIButton *switchButton;
@property (strong, nonatomic) UIButton *flashButton;
@property (strong, nonatomic) UIButton *backBtn;
@property (nonatomic, strong) UILabel *tipLabel;
@property (strong, nonatomic) FBCameraProgressView *progressView;
//记录录制的时间 默认最大60秒
@property (assign, nonatomic) NSInteger seconds;
/** 记录是否为录像 */
@property (nonatomic, assign) BOOL isVideo;
@end
//时间大于这个就是视频，否则为拍照
#define TimeMax 1

#define kDefaultVideoDuration  60

@implementation FBCameraHomeViewController

- (void)dealloc {
//    self.camera = nil;
    [self.camera stop];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // start the camera
    [self.camera start];
    if (self.tipLabel) {
        if (self.cameraType == FBCameraTypePhoto) {
            self.tipLabel.text = @"轻触拍照";
        } else if (self.cameraType == FBCameraTypeVideo) {
            self.tipLabel.text = @"长按录制";
        }
        self.tipLabel.alpha = 1;
    }
    __weak __typeof(self)weakSelf = self;
    [UIView animateWithDuration:2.0 animations:^{
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.tipLabel.alpha = 0;
    }];
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.camera stopRecording];

    [self.camera stop];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:animated];

}

- (void)initialUI {
    
    self.view.backgroundColor = [UIColor blackColor];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    
    // ----- initialize camera -------- //
    
    // create camera vc
    self.camera = [[LLSimpleCamera alloc] initWithQuality:AVCaptureSessionPresetHigh
                                                 position:LLCameraPositionRear
                                             videoEnabled:YES];
    self.camera.useDeviceOrientation = YES;
    self.camera.zoomingEnabled = YES;
    self.camera.maxScale = 4;
    self.camera.tapToFocusImage = [UIImage imageNamed:@"FB_ChatCamera_point"];
    // attach to a view controller
    [self.camera attachToViewController:self withFrame:CGRectMake(0, 0, screenRect.size.width, screenRect.size.height)];
    
    self.camera.fixOrientationAfterCapture = YES;
    
    // take the required actions on a device change
    __weak typeof(self) weakSelf = self;
    [self.camera setOnDeviceChange:^(LLSimpleCamera *camera, AVCaptureDevice * device) {
        
        NSLog(@"Device changed.");
        
        // device changed, check if flash is available
        if([camera isFlashAvailable]) {
            weakSelf.flashButton.hidden = NO;
            
            if(camera.flash == LLCameraFlashOff) {
                weakSelf.flashButton.selected = NO;
            }
            else {
                weakSelf.flashButton.selected = YES;
            }
        }
        else {
            weakSelf.flashButton.hidden = YES;
        }
    }];
    
    [self.camera setOnError:^(LLSimpleCamera *camera, NSError *error) {
        NSLog(@"Camera error: %@", error);
        
        if([error.domain isEqualToString:LLSimpleCameraErrorDomain]) {
            if(error.code == LLSimpleCameraErrorCodeCameraPermission ||
               error.code == LLSimpleCameraErrorCodeMicrophonePermission) {
                
                if(weakSelf.errorLabel) {
                    [weakSelf.errorLabel removeFromSuperview];
                }
                
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
                label.text = @"We need permission for the camera.\nPlease go to your settings.";
                label.numberOfLines = 2;
                label.lineBreakMode = NSLineBreakByWordWrapping;
                label.backgroundColor = [UIColor clearColor];
                label.font = [UIFont fontWithName:@"AvenirNext-DemiBold" size:13.0f];
                label.textColor = [UIColor whiteColor];
                label.textAlignment = NSTextAlignmentCenter;
                [label sizeToFit];
                label.center = CGPointMake(screenRect.size.width / 2.0f, screenRect.size.height / 2.0f);
                weakSelf.errorLabel = label;
                [weakSelf.view addSubview:weakSelf.errorLabel];
            }
        }
    }];
    
    // ----- camera buttons -------- //
    
    self.progressView = [[FBCameraProgressView alloc] init];
    self.progressView.frame = CGRectMake(0, 0, 72, 72);
    self.progressView.hidden = NO;
    self.progressView.clipsToBounds = YES;
    self.progressView.autoresizesSubviews = YES;
    self.progressView.opaque = YES;
//    self.progressView.backgroundColor = [UIColor colorWithRed:0.847 green:0.831 blue:0.816 alpha:1.000];
    self.progressView.backgroundColor = kHEXAColor(0xE2E2E2, 0.75);
    [self.view addSubview:self.progressView];
    
    self.tipLabel = [[UILabel alloc] init];
    self.tipLabel.textAlignment = NSTextAlignmentCenter;
    self.tipLabel.text = @"轻触拍照，按住摄像";
    self.tipLabel.textColor = [UIColor whiteColor];
    self.tipLabel.font = [UIFont systemFontOfSize:14.f];
    self.tipLabel.alpha = 1;
    [self.tipLabel sizeToFit];
    [self.view addSubview:self.tipLabel];
    
    // snap button to capture image
    self.snapButton = [[UIImageView alloc] init];
    self.snapButton.frame = CGRectMake(0, 0, 52, 52);
    self.snapButton.clipsToBounds = YES;
    self.snapButton.layer.cornerRadius = self.snapButton.width / 2.0f;
    self.snapButton.layer.borderColor = [UIColor whiteColor].CGColor;
    self.snapButton.layer.borderWidth = 10.0f;
    self.snapButton.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:1];
    self.snapButton.layer.rasterizationScale = [UIScreen mainScreen].scale;
    self.snapButton.layer.shouldRasterize = YES;
//    self.snapButton.image = [UIImage imageNamed:@"FBChatCamera_take"];
    self.snapButton.userInteractionEnabled = YES;
    [self.view addSubview:self.snapButton];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSnapButton:)];
    [self.snapButton addGestureRecognizer:tap];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressSnap:)];
    longPress.minimumPressDuration = 0.7;
    longPress.numberOfTouchesRequired = 1;
    [self.snapButton addGestureRecognizer:longPress];
    
    // button to toggle flash
    self.flashButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.flashButton.frame = CGRectMake(0, 0, 16.0f + 20.0f, 24.0f + 20.0f);
    self.flashButton.tintColor = [UIColor whiteColor];
    [self.flashButton setImage:[UIImage imageNamed:@"camera-flash.png"] forState:UIControlStateNormal];
    self.flashButton.imageEdgeInsets = UIEdgeInsetsMake(10.0f, 10.0f, 10.0f, 10.0f);
    [self.flashButton addTarget:self action:@selector(flashButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.flashButton];
    
    if([LLSimpleCamera isFrontCameraAvailable] && [LLSimpleCamera isRearCameraAvailable]) {
        // button to toggle camera positions
        self.switchButton = [UIButton buttonWithType:UIButtonTypeSystem];
        self.switchButton.frame = CGRectMake(0, 0, 44, 44);
        self.switchButton.contentMode = UIViewContentModeScaleAspectFit;
        self.switchButton.tintColor = [UIColor whiteColor];
        [self.switchButton setImage:[UIImage imageNamed:@"FB_photo_change"] forState:UIControlStateNormal];
        [self.switchButton addTarget:self action:@selector(switchButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.switchButton];
    }
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backBtn.frame = CGRectMake(0, 0, 40, 40);
    [self.backBtn setImage:[UIImage imageNamed:@"FB_ChatCamera_back"] forState:UIControlStateNormal];
    [self.backBtn addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backBtn];
    
    
    self.camera.view.frame = self.view.contentBounds;
    
    self.snapButton.layer.cornerRadius = self.snapButton.width * 0.5;
    self.snapButton.center = self.view.contentCenter;
    self.snapButton.bottom = self.view.height - 58.0f;
    
    self.tipLabel.center = self.view.contentCenter;
    self.tipLabel.bottom = self.view.height - 90 - 46;
    
    self.progressView.layer.cornerRadius = self.progressView.width * 0.5;
//    self.progressView.center = self.view.contentCenter;
//    self.progressView.bottom = self.view.height - 50.0f;
    self.progressView.center = self.snapButton.center;
    
    self.flashButton.center = self.view.contentCenter;
    self.flashButton.top = 5.0f;
    
    self.switchButton.top = 15.0f;
    self.switchButton.right = self.view.width - 15.0f;
    
    self.backBtn.right = self.progressView.left - 50;
//    self.backBtn.bottom = self.view.height - 55.0f;
    self.backBtn.center = self.snapButton.center;
    self.backBtn.right = self.progressView.right - 55 - self.progressView.width;
    
    self.progressView.layer.cornerRadius = self.progressView.frame.size.width/2;
    
}

- (void)back:(UIButton *)btn {
//    [self dismissViewControllerAnimated:YES completion:nil];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self backFunction];
    });
}

/* camera button methods */

- (void)switchButtonPressed:(UIButton *)button {
    [self.camera togglePosition];
}

- (NSURL *)applicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSInteger)HSeconds {
    if (_HSeconds == 0) {
        _HSeconds = kDefaultVideoDuration;
    }
    return _HSeconds;
}

- (void)flashButtonPressed:(UIButton *)button {
    if(self.camera.flash == LLCameraFlashOff) {
        BOOL done = [self.camera updateFlashMode:LLCameraFlashOn];
        if(done) {
            self.flashButton.selected = YES;
            self.flashButton.tintColor = [UIColor yellowColor];
        }
    } else {
        BOOL done = [self.camera updateFlashMode:LLCameraFlashOff];
        if(done) {
            self.flashButton.selected = NO;
            self.flashButton.tintColor = [UIColor whiteColor];
        }
    }
}

- (void)tapSnapButton:(UITapGestureRecognizer *)tap {
    if (self.cameraType == FBCameraTypeVideo) {
        return;
    }
    // capture
    __weak __typeof(self)weakSelf = self;
    [self.camera capture:^(LLSimpleCamera *camera, UIImage *image, NSDictionary *metadata, NSError *error) {
        if(!error) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            [strongSelf.camera stop];

            FBCameraImageViewController *imageVC = [[FBCameraImageViewController alloc] initWithImage:image handler:^(UIImage *image) {
                if (strongSelf.imageHandler) {
                    strongSelf.imageHandler(image, strongSelf);
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [strongSelf backFunction];
                });
            }];
            [strongSelf.camera stop];

            [strongSelf presentViewController:imageVC animated:NO completion:nil];
        } else {
            NSLog(@"An error has occured: %@", error);
        }
    } exactSeenImage:YES];
}



- (void)endRecord {
    [self.camera stop];

    [self.camera stopRecording];
    [self.progressView clearProgress];
    self.seconds = self.HSeconds;
    
    self.snapButton.size = CGSizeMake(52, 52);
    self.snapButton.layer.cornerRadius = self.snapButton.width * 0.5;
    self.snapButton.center = self.view.contentCenter;
    self.snapButton.bottom = self.view.height - 58.0f;
    
    self.progressView.frame = CGRectMake(0, 0, 72, 72);
    self.progressView.layer.cornerRadius = self.progressView.width * 0.5;
    //    self.progressView.center = self.view.contentCenter;
    //    self.progressView.bottom = self.view.height - 50.0f;
    self.progressView.center = self.snapButton.center;

}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

- (void)onStartTranscribe {
    -- self.seconds;
    if (self.seconds > 0) {
        if (self.HSeconds - self.seconds >= TimeMax && !self.isVideo) {
            self.isVideo = YES;//长按时间超过TimeMax 表示是视频录制
            self.progressView.hidden = NO;
            self.progressView.timeMax = self.seconds;
        }
        [self performSelector:@selector(onStartTranscribe) withObject:nil afterDelay:1.0];
    } else {
        if (self.camera.isRecording) {
            [self endRecord];
        }
    }
}

/* other lifecycle methods */

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    


}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (UIInterfaceOrientation) preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}

- (void)cameraPickerImageComplate:(FBCameraPickeImageHandler)imageHandler videoComplate:(FBCameraPickeVideoHandler)videoHandler {
    self.imageHandler = imageHandler;
    self.videoHandler = videoHandler;
}

- (void)backFunction {
    [self.camera stopRecording];
    [self.camera stop];
    self.camera = nil;
    if ([self viewController].navigationController.topViewController == [self viewController]) {
        [[self viewController].navigationController popViewControllerAnimated:YES];
    }
    else {
        [[self viewController] dismissViewControllerAnimated:YES completion:nil];
    }

}

- (UIViewController *)viewController{
    UIResponder *next = [self nextResponder];
    do{
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        }
        next = [next nextResponder];
    } while (next);
    return nil;
}
@end
